<!DOCTYPE html>
<html lang="en">
	<head>
		<title>火影忍者！</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<style>
			html,body{
                width:100%;
                height:100%
            }

			body {
				font-family: Monospace;
				background-color: #000;
				color: #fff;
				margin: 0px;
				overflow: hidden;
				background: url(img/Naruto.jpg) no-repeat;
				background-size: 100%;
			}

			#info {
				color: #fff;
				position: absolute;
				top: 10px;
				width: 100%;
				text-align: center;
				z-index: 100;
				display: block;
			}

			input {
				/* color: #f00;
				font-weight: bold;
				text-decoration: underline;
				cursor: pointer */
				border:1px solid #b42323;
                box-shadow: 0 1px 2px #e99494 inset,0 -1px 0 #954b4b inset,0 -2px 3px #e99494 inset;
                background: -webkit-linear-gradient(top,#d53939,#b92929);
                background: -moz-linear-gradient(top,#d53939,#b92929);
                background: linear-gradient(top,#d53939,#b92929);
				height: 50px;
				width: 100px;
			}
			#video {
			    position: absolute;
			    top: 0;
			    left: 0;
			    z-index: -1;
			}
			.footer {
			    position: fixed;
			    bottom: 10px;
			
			    width: 100%;
			    text-align: center;
			
			    z-index: 100000;
					
			}
			progress
			{
          color:orange; /*兼容IE10的已完成进度背景*/
          border:none;
          background:#d7d7d7;/*这个属性也可当作Chrome的已完成进度背景，只不过被下面的::progress-bar覆盖了*/      
      }

      progress::-webkit-progress-bar
      {
          background:#d7d7d7;
      }

      progress::-webkit-progress-value,
			progress::-moz-progress-bar
     {
     background:orange;
     }
		</style>
	</head>

	<body>
		<!-- 		<div id="info">
		<a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - OBJLoader + MTLLoader
		</div> -->
		<video id="video" playsinline="">

		</video>

		<div class="footer">
			<input type="button" value="开启AR" id="openCamera" />
			<!-- <progress max="100" value="0" id="pg">正在加载模型中。。。。</progress> -->
			<p id="jindu"></p>
		</div>
		<script src="libs/three/three.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/inflate.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="libs/three/FBXLoader.js" type="text/javascript" charset="utf-8"></script>
		<script src="libs/three/OrbitControls.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/stats.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/dat.gui.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="https://cdn.bootcss.com/dat-gui/0.7.1/dat.gui.min.js"></script>
		<script src="js/Detector.js"></script>

		<!-- <script src="js/webar.js" type="text/javascript" charset="utf-8"></script> -->
		<script>
			var video = document.getElementById('video');
			var constraints = {
				audio: false,
				video: {
					width: window.innerWidth,
					height: window.innerHeight
				},
			};
			// 			init();
			// 			animate();
			document.querySelector('#openCamera').addEventListener('click', function() {
				if (navigator.mediaDevices.getUserMedia) {
					//最新标准API
					navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
					console.log("success");
				} else if (navigator.webkitGetUserMedia) {
					//webkit核心浏览器
					navigator.webkitGetUserMedia(constraints, success, error);
				} else if (navigator.mozGetUserMedia) {
					//firefox浏览器
					navigator.mozGetUserMedia(constraints, success, error);
				} else if (navigator.getUserMedia) {
					//旧版API
					navigator.getUserMedia(constraints, success, error);
				}
				//成功回调函数
				function success(stream) {

					// 打开摄像头成功
					// 将视频铺满全屏(简单处理)
					let videoWidth = video.offsetWidth;
					let videoHeight = video.offsetHeight;

					if (window.innerWidth < window.innerHeight) {
						// 竖屏
						if (videoHeight < window.innerHeight) {
							video.setAttribute('height', window.innerHeight.toString() + 'px');
						}
					} else {
						// 横屏
						if (videoWidth < window.innerWidth) {
							video.setAttribute('width', window.innerWidth.toString() + 'px');
						}
					}
					//兼容webkit核心浏览器
					var CompatibleURL = window.URL || window.webkitURL;
					//将视频流转化为video的源
					video.src = CompatibleURL.createObjectURL(stream);
					video.play(); //播放视频
					document.querySelector("#openCamera").hidden = true;

					draw();
				}

				function error(error) {
					console.log('访问用户媒体失败：', error.name, error.message);
				}
			}, false);


			var renderer, camera, scene, gui, light, stats, controls, meshHelper, mixer, action, datGui;
			var clock = new THREE.Clock();


			function initRender() {
				renderer = new THREE.WebGLRenderer({
					antialias: true,
					alpha: true
				});
				renderer.setPixelRatio(window.devicePixelRatio);
				renderer.setSize(window.innerWidth, window.innerHeight);
				// renderer.setClearColor(0xeeeeee);
				// renderer.shadowMap.enabled = true;
				//告诉渲染器需要阴影效果
				document.body.appendChild(renderer.domElement);
			}

			function initCamera() {
				camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 2000);
				camera.position.set(100, 200, 300);
			}

			function initScene() {
				scene = new THREE.Scene();
				// scene.background = new THREE.Color(0xa0a0a0);
				// scene.fog = new THREE.Fog(0xa0a0a0, 200, 1000);
			}

			//初始化dat.GUI简化试验流程
			function initGui() {
				//声明一个保存需求修改的相关数据的对象
				gui = {
					helper: true //模型辅助线
				};
				datGui = new dat.GUI();
				//将设置属性添加到gui当中，gui.add(对象，属性，最小值，最大值）

				datGui.add(gui, "helper").onChange(function(e) {
					meshHelper.visible = e;
				})
			}

			function initLight() {
				scene.add(new THREE.AmbientLight(0x444444));

				light = new THREE.DirectionalLight(0xffffff);
				light.position.set(0, 200, 100);

				light.castShadow = true;
				light.shadow.camera.top = 180;
				light.shadow.camera.bottom = -100;
				light.shadow.camera.left = -120;
				light.shadow.camera.right = 120;

				//告诉平行光需要开启阴影投射
				light.castShadow = true;

				scene.add(light);
			}

			function initModel() {

				//辅助工具
				//         var helper = new THREE.AxesHelper(50);
				//         scene.add(helper);

				// 地板
				//         var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2000, 2000 ), new THREE.MeshPhongMaterial( { color: 0xffffff, depthWrite: false } ) );
				//         mesh.rotation.x = - Math.PI / 2;
				//         mesh.receiveShadow = true;
				//         scene.add( mesh );

				//添加地板割线
				//         var grid = new THREE.GridHelper( 2000, 20, 0x000000, 0x000000 );
				//         grid.material.opacity = 0.2;
				//         grid.material.transparent = true;
				//         scene.add( grid );

				//加载模型
				var loader = new THREE.FBXLoader();
				loader.load("model/Naruto.fbx", function(mesh) {

					console.log(mesh);

					//添加骨骼辅助
					//             meshHelper = new THREE.SkeletonHelper(mesh);
					//             scene.add(meshHelper);

					//设置模型的每个部位都可以投影
					mesh.traverse(function(child) {
						if (child.isMesh) {
							child.castShadow = true;
							child.receiveShadow = true;
						}
					});

					//AnimationMixer是场景中特定对象的动画播放器。当场景中的多个对象独立动画时，可以为每个对象使用一个AnimationMixer
					mixer = mesh.mixer = new THREE.AnimationMixer(mesh);

					//mixer.clipAction 返回一个可以控制动画的AnimationAction对象  参数需要一个AnimationClip 对象
					//AnimationAction.setDuration 设置一个循环所需要的时间，当前设置了一秒
					//告诉AnimationAction启动该动作
					//action = mixer.clipAction(mesh.animations[0]);
					//action.play();

					var actions = []; //所有的动画数组
					var animations = datGui.addFolder("animations");

					for (var i = 0; i < mesh.animations.length; i++) {
						createAction(i);
					}

					function createAction(i) {
						actions[i] = mixer.clipAction(mesh.animations[i]);
						gui["action" + i] = function() {
							for (var j = 0; j < actions.length; j++) {
								if (j === i) {
									actions[j].play();
								} else {
									actions[j].stop();
								}
							}
						};

						animations.add(gui, "action" + i);
					}

					//添加暂停所有动画的按键
					gui.stop = function() {
						for (var i = 0; i < actions.length; i++) {
							actions[i].stop();
						}
					};

					datGui.add(gui, "stop");

					mesh.position.y += 100;

					scene.add(mesh);
				});
			}

			//初始化性能插件
			function initStats() {
				stats = new Stats();
				document.body.appendChild(stats.dom);
			}

			function initControls() {

				controls = new THREE.OrbitControls(camera, renderer.domElement);
				//设置控制器的中心点
				//controls.target.set( 0, 100, 0 );
				// 如果使用animate方法时，将此函数删除
				//controls.addEventListener( 'change', render );
				// 使动画循环使用时阻尼或自转 意思是否有惯性
				controls.enableDamping = true;
				//动态阻尼系数 就是鼠标拖拽旋转灵敏度
				//controls.dampingFactor = 0.25;
				//是否可以缩放
				controls.enableZoom = true;
				//是否自动旋转
				controls.autoRotate = false;
				controls.autoRotateSpeed = 0.5;
				//设置相机距离原点的最远距离
				controls.minDistance = 1;
				//设置相机距离原点的最远距离
				controls.maxDistance = 2000;
				//是否开启右键拖拽
				controls.enablePan = true;
			}

			function render() {

				var time = clock.getDelta();
				if (mixer) {
					mixer.update(time);
				}

				controls.update();
			}

			//窗口变动触发的函数
			function onWindowResize() {

				camera.aspect = window.innerWidth / window.innerHeight;
				camera.updateProjectionMatrix();
				renderer.setSize(window.innerWidth, window.innerHeight);
			}

			function animate() {
				//更新控制器
				render();

				//更新性能插件
				stats.update();

				renderer.render(scene, camera);

				requestAnimationFrame(animate);
			}

			function draw() {
				//兼容性判断
				if (!Detector.webgl) Detector.addGetWebGLMessage();

				initGui();
				initRender();
				initScene();
				initCamera();
				initLight();
				initModel();
				initControls();
				initStats();

				animate();
				window.onresize = onWindowResize;
			}
		</script>

	</body>
</html>
